import { NEW_FILE, OPEN_FILE, SAVE_FILE, OPEN_FOLDER } from '@msg/file'
import { ipcMain } from 'electron'
import { readFileSync, writeFileSync, readdirSync, statSync } from 'fs'

// 打开文件
ipcMain.on(OPEN_FILE, (e, path) => {
  const file = readFileSync(path)
  e.sender.send(`${OPEN_FILE}-render`, file.toString(), path)
})

// 保存文件
ipcMain.on(SAVE_FILE, (e, content, path) => {
  writeFileSync(path, content)
  e.sender.send(`${SAVE_FILE}-render`, true)
})

const loadDir = (dir, path, arr) => {
  dir.forEach((name) => {
    const childPath = `${path}/${name}`
    const stat = statSync(childPath)
    if (stat.isFile()) {
      arr.push({ name, path: childPath, children: [] })
    } else if (stat.isDirectory()) {
      arr.push({ name, path: childPath, children: [] })
      loadDir(readdirSync(childPath), childPath, arr[arr.length - 1].children)
    }
  })
}
// 打开文件夹
ipcMain.on(OPEN_FOLDER, (e, name, path) => {
  const dir = readdirSync(path)
  const folder = [{ name, path, children: [] }]
  loadDir(dir, path, folder)
  e.sender.send(`${OPEN_FOLDER}-render`, folder)
})
